<script setup lang="ts">
import { ref, reactive, onMounted } from "vue"
import { useHttp } from "@/hooks/useHttp"
import { type SendVipLogDto, donateVipApi, type DonateVipReq } from "@/api/donate"
import { ElMessage, type FormInstance, type FormRules } from "element-plus"
import { Loading, CircleCheck } from "@element-plus/icons-vue"
import { checkUserNoApi } from "@/api/user"

// 查询参数
interface SearchType {
  userNo: string;
  operator: string;
  vipLevel: number | null;
}

const searchParams = ref<SearchType>({
  userNo: "",
  operator: "",
  vipLevel: null
})

// 赠送VIP相关
const addVipDialogVisible = ref(false)
const addVipLoading = ref(false)
const addVipFormRef = ref<FormInstance>()

const addVipForm = reactive({
  userNo: '',
  vipLevel: undefined as number | undefined,
  day: undefined as number | undefined,
  reason: ''
})

// 用户编号校验相关
const userNoValidating = ref(false)
const userNoValid = ref(false)
const currentUserInfo = ref<{
  avatar?: string;
  nickname?: string;
}>({})

// 赠送VIP表单验证规则
const addVipRules: FormRules = {
  userNo: [
    { required: true, message: '请输入用户编号', trigger: 'blur' },
    { 
      validator: async (rule: any, value: string, callback: any) => {
        if (!value) {
          callback()
          return
        }
        
        try {
          userNoValidating.value = true
          const response = await checkUserNoApi(value)
          if (response.code === 200 && response.data) {
            userNoValid.value = true
            // 保存用户信息
            currentUserInfo.value = {
              avatar: response.data.avatar,
              nickname: response.data.nickname
            }
            callback()
          } else {
            userNoValid.value = false
            currentUserInfo.value = {}
            callback(new Error('用户编号不存在'))
          }
        } catch (error) {
          userNoValid.value = false
          currentUserInfo.value = {}
          callback(new Error('用户编号验证失败'))
        } finally {
          userNoValidating.value = false
        }
      }, 
      trigger: 'blur' 
    }
  ],
  vipLevel: [
    { required: true, message: '请选择VIP等级', trigger: 'change' }
  ],
  day: [
    { required: true, message: '请选择天数', trigger: 'change' }
  ],
  reason: [
    { required: true, message: '请输入赠送原因', trigger: 'blur' }
  ]
}

// 使用封装的 useHttp hook，配置自定义参数名
const { 
  dataList,
  loading,
  totals,
  pageInfo,
  loadData,
  handleSizeChange,
  handleCurrentChange,
  resetPagination
} = useHttp<SendVipLogDto>("/donate/vipPage", searchParams, {
  pageKey: 'pageIndex',    // 使用 pageIndex 而不是 page
  pageSizeKey: 'pageSize', // 使用 pageSize
  totalKey: 'total',       // 使用 total
  listKey: 'list'          // 使用 list
});

// 查询方法
const handleSearch = () => {
  resetPagination()
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
}

// 重置方法
const handleReset = () => {
  searchParams.value = {
    userNo: "",
    operator: "",
    vipLevel: null
  }
  resetPagination()
  // resetPagination() 内部已经调用了 loadData()，不需要重复调用
}

// 获取VIP标签颜色类型
const getVipTagType = (vipLevel: number) => {
  switch (vipLevel) {
    case 1:
      return 'info'      // 蓝色
    case 2:
      return 'success'   // 绿色
    case 3:
      return 'warning'   // 橙色
    case 4:
      return 'danger'    // 红色
    case 5:
      return ''          // 默认灰色
    default:
      return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (dateString: string) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 打开赠送VIP弹窗
const handleAddVip = () => {
  addVipDialogVisible.value = true
}

// 取消赠送VIP
const handleCancelAddVip = () => {
  addVipDialogVisible.value = false
  // 重置表单
  Object.assign(addVipForm, {
    userNo: '',
    vipLevel: undefined,
    day: undefined,
    reason: ''
  })
  // 重置用户编号校验状态
  userNoValid.value = false
  userNoValidating.value = false
  currentUserInfo.value = {}
  addVipFormRef.value?.clearValidate()
}

// 确认赠送VIP
const handleConfirmAddVip = async () => {
  if (!addVipFormRef.value) return
  
  try {
    await addVipFormRef.value.validate()
    addVipLoading.value = true
    
    const requestData: DonateVipReq = {
      userNo: addVipForm.userNo,
      vipLevel: addVipForm.vipLevel!,
      day: addVipForm.day!,
      reason: addVipForm.reason
    }
    
    await donateVipApi(requestData)
    ElMessage.success('VIP赠送成功')
    addVipDialogVisible.value = false
    addVipFormRef.value?.resetFields()
    addVipFormRef.value?.clearValidate()
    // 刷新列表
    loadData()
  } catch (error) {
    console.error('赠送VIP失败:', error)
    ElMessage.error('赠送VIP失败')
  } finally {
    addVipLoading.value = false
  }
}

// 组件挂载时加载数据
onMounted(() => {
  loadData()
})
</script>

<template>
  <div class="send-vip">
    <!-- 查询区域 -->
    <el-card class="mb">
      <el-form :model="searchParams" inline>
        <el-form-item label="用户编号">
          <el-input 
            v-model="searchParams.userNo" 
            placeholder="请输入用户编号" 
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="操作者">
          <el-input 
            v-model="searchParams.operator" 
            placeholder="请输入操作者" 
            clearable
            style="width: 200px;"
          />
        </el-form-item>
        <el-form-item label="VIP等级">
                     <el-select 
             v-model="searchParams.vipLevel" 
             placeholder="请选择VIP等级"
             clearable
             style="width: 200px;"
           >
             <el-option label="VIP1" :value="1" />
             <el-option label="VIP2" :value="2" />
             <el-option label="VIP3" :value="3" />
             <el-option label="VIP4" :value="4" />
             <el-option label="VIP5" :value="5" />
           </el-select>
        </el-form-item>
                 <el-form-item>
           <el-button type="primary" @click="handleSearch">查询</el-button>
           <el-button @click="handleReset">重置</el-button>
           <el-button type="success" @click="handleAddVip">赠送VIP</el-button>
         </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card>
      <el-table 
        :data="dataList" 
        v-loading="loading"
        style="width: 100%"
        :fit="true"
      >
        <el-table-column prop="id" label="记录ID" min-width="200" show-overflow-tooltip />
        <el-table-column prop="userNo" label="用户编号" min-width="120" />
                 <el-table-column prop="vipLevel" label="VIP等级" width="100" align="center">
           <template #default="{ row }">
             <el-tag :type="getVipTagType(row.vipLevel)">VIP{{ row.vipLevel }}</el-tag>
           </template>
         </el-table-column>
        <el-table-column prop="day" label="天数" width="100" align="center">
          <template #default="{ row }">
            <span>{{ row.day }}天</span>
          </template>
        </el-table-column>
                 <el-table-column prop="packageId" label="礼包ID" min-width="200" show-overflow-tooltip />
         <el-table-column prop="reason" label="原因" min-width="150" show-overflow-tooltip>
           <template #default="{ row }">
             <span>{{ row.reason || '-' }}</span>
           </template>
         </el-table-column>
        <el-table-column prop="operator" label="操作者" min-width="120" />
        <el-table-column prop="createTime" label="创建时间" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="modifyTime" label="修改时间" min-width="200" show-overflow-tooltip>
          <template #default="{ row }">
            {{ formatDateTime(row.modifyTime) }}
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination 
        class="pagination-center mt mb"
        v-model:current-page="pageInfo.page" 
        v-model:page-size="pageInfo.pageSize"
        :page-sizes="[10, 20, 30, 50]" 
        layout="sizes, prev, pager, next, jumper, total" 
        :total="totals" 
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" 
        background
             />
     </el-card>

     <!-- 赠送VIP弹窗 -->
     <el-dialog
       v-if="addVipDialogVisible"
       v-model="addVipDialogVisible"
       title="赠送VIP"
       width="500px"
       :close-on-click-modal="false"
       @close="handleCancelAddVip"
     >
       <el-form
         ref="addVipFormRef"
         :model="addVipForm"
         :rules="addVipRules"
         label-width="100px"
       >
                   <el-form-item label="用户编号" prop="userNo">
            <el-input
              v-model="addVipForm.userNo"
              placeholder="请输入用户编号"
              clearable
              :loading="userNoValidating"
            >
              <template #suffix>
                <el-icon v-if="userNoValidating" class="is-loading">
                  <Loading />
                </el-icon>
                <el-icon v-else-if="userNoValid" style="color: #67c23a;">
                  <CircleCheck />
                </el-icon>
              </template>
            </el-input>
            <!-- 用户信息显示 -->
            <div v-if="userNoValid && currentUserInfo.nickname" class="user-info-display">
              <el-avatar 
                :size="32" 
                :src="currentUserInfo.avatar" 
                class="user-avatar"
              />
              <span class="user-nickname">{{ currentUserInfo.nickname }}</span>
            </div>
          </el-form-item>
         
         <el-form-item label="VIP等级" prop="vipLevel">
           <el-select
             v-model="addVipForm.vipLevel"
             placeholder="请选择VIP等级"
             clearable
             style="width: 100%"
           >
             <el-option label="VIP1" :value="1" />
             <el-option label="VIP2" :value="2" />
             <el-option label="VIP3" :value="3" />
             <el-option label="VIP4" :value="4" />
             <el-option label="VIP5" :value="5" />
           </el-select>
         </el-form-item>
         
         <el-form-item label="天数" prop="day">
           <el-select
             v-model="addVipForm.day"
             placeholder="请选择天数"
             clearable
             style="width: 100%"
           >
             <el-option label="1天" :value="1" />
             <el-option label="3天" :value="3" />
             <el-option label="5天" :value="5" />
             <el-option label="7天" :value="7" />
             <el-option label="10天" :value="10" />
             <el-option label="15天" :value="15" />
             <el-option label="30天" :value="30" />
           </el-select>
         </el-form-item>
         
         <el-form-item label="原因" prop="reason">
           <el-input
             v-model="addVipForm.reason"
             type="textarea"
             :rows="3"
             placeholder="请输入赠送原因"
             maxlength="200"
             show-word-limit
           />
         </el-form-item>
       </el-form>
       
       <template #footer>
         <div class="dialog-footer">
           <el-button @click="handleCancelAddVip">取消</el-button>
           <el-button
             type="primary"
             :loading="addVipLoading"
             @click="handleConfirmAddVip"
           >
             确定赠送
           </el-button>
         </div>
       </template>
     </el-dialog>
   </div>
 </template>

<style lang="less" scoped>
.send-vip {
  font-size: 16px;
  
  .mb {
    margin-bottom: 20px;
  }
  
  .mt {
    margin-top: 20px;
  }
  
  .pagination-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }
  
     // 表格字体大小和行间距
   :deep(.el-table) {
     font-size: 16px;
     
     .el-table__header {
       th {
         font-size: 16px;
         font-weight: 600;
         padding: 16px 0;  // 增加表头行高
       }
     }
     
     .el-table__body {
       td {
         font-size: 16px;
         padding: 16px 0;  // 增加表格行高
       }
       
       tr {
         height: auto;  // 让行高自适应内容
       }
     }
     
     // 增加行间距
     .el-table__row {
       height: 60px;  // 设置固定的行高
     }
   }
  
  // 表单字体大小
  :deep(.el-form) {
    .el-form-item__label {
      font-size: 16px;
    }
    
    .el-input__inner {
      font-size: 16px;
    }
    
    .el-select .el-input__inner {
      font-size: 16px;
    }
  }
  
  // 按钮字体大小
  :deep(.el-button) {
    font-size: 16px;
  }
  
     // 分页字体大小
   :deep(.el-pagination) {
     font-size: 16px;
   }
   
       // 弹窗样式
    .dialog-footer {
      text-align: right;
    }
    
    // 用户信息显示样式
    .user-info-display {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-top: 8px;
      padding: 8px 12px;
      background-color: #f5f7fa;
      border-radius: 4px;
      border: 1px solid #e4e7ed;
      
      .user-avatar {
        flex-shrink: 0;
      }
      
      .user-nickname {
        font-size: 14px;
        color: #606266;
        font-weight: 500;
      }
    }
 }
</style>